package com.atm.bulksms;

import java.util.ArrayList;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.opengl.Visibility;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckedTextView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;

import com.atm.bulksms.data.ContactAdapter;
import com.atm.bulksms.data.ContactItem;
import com.atm.bulksms.dialog.NumberListDialog;
import com.atm.bulksms.util.Constants;
import com.atm.bulksms.util.Utils;


public class ContactChooser extends ListActivity implements OnItemClickListener{
	
	private static final byte DIALOG_NUMBER_LIST = 0;
	private static final byte DIALOG_CLEAR_DATA_ALERT = 1;
	private static final String PHONE = "PHONE";
	private static final String NAME = "NAME";
	
	int listType = Constants.LIST_TYPE_SELECT_CONTACT;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.contact_list);
		Bundle extra = getIntent().getExtras();
		if(extra != null)
			listType = extra.getInt(Constants.LIST_TYPE);
        final ContactAdapter adapter = new ContactAdapter(this, android.R.layout.simple_list_item_multiple_choice, getCursor(""),
        	
	new String[] {ContactsContract.Data.DISPLAY_NAME}, new int[] {android.R.id.text1});
        
        setListAdapter(adapter);
        final ListView listView = getListView();

        listView.setItemsCanFocus(false);
        listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
        listView.setOnItemClickListener(this);
        
        
        EditText searchView = (EditText)findViewById(R.id.search_view);
        searchView.addTextChangedListener(new TextWatcher(){

			@Override
			public void afterTextChanged(Editable arg0) {
				adapter.changeCursor(getCursor(arg0.toString()));
			}

		
	@Override
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
				// TODO Auto-generated method stub
			
	
			}
        	
        });
        
        Button doneBtn = (Button) findViewById(R.id.contact_list_done);
       
        doneBtn.setOnClickListener(new View.OnClickListener(){

			@Override
			public void onClick(View v) {
				if(listType == Constants.LIST_TYPE_CREATE_GROUP){
            	
	setResult(RESULT_OK, new Intent());
            	}
				finish();
			}});
	}

	private Cursor getCursor(String name) {
		String[]proj = new String[] {ContactsContract.Contacts._ID, ContactsContract.Contacts.DISPLAY_NAME, ContactsContract.Contacts.HAS_PHONE_NUMBER};
		  // Query for people
      Cursor cursor = managedQuery(ContactsContract.Contacts.CONTENT_URI,
              proj, ContactsContract.Contacts.DISPLAY_NAME +" LIKE \'"+name+"%\' AND "+ContactsContract.Contacts.HAS_PHONE_NUMBER+">0", null, ContactsContract.Contacts.DISPLAY_NAME+" ASC");
      return cursor;
	}

	
	CheckedTextView selectedView = null;
	
	@Override
	public void onItemClick(AdapterView<?> arg0, View view, int position, long id) {
		
		selectedView = (CheckedTextView)view;
		if(!selectedView.isEnabled()) return;
	 
		System.out.println(" selected contact  "+getListAdapter().getItem(position));
		Cursor c = (Cursor)getListAdapter().getItem(position);
		//String phoneCount = c.getString(c.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER));
		String name = c.getString(c.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		contactId = c.getInt(c.getColumnIndex(ContactsContract.Contacts._ID));
		boolean checked = Utils.hasContact(contactId, name);
		System.out.println(" Is checked --"+checked);
		
		/*if(Integer.parseInt(phoneCount) > 0){
			System.out.println(" It has phone number");
		}*/
		// String contactId = c.getString(c.getColumnIndex(ContactsContract.Contacts._ID));
		 Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null,ContactsContract.Contacts.DISPLAY_NAME +" = \'"+ name+"\'" ,null, null);
            ArrayList<String> phoneNumbers = new ArrayList<String>(3);
            System.out.println("count "+phones.getCount());
            while (phones.moveToNext()) 
            {
              String phoneNumber = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
              int type = phones.getInt(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
              System.out.println(" Type "+type+" :: "+phoneNumber);
              // 1- home   2- mobile 3 - work  
              if(!phoneNumbers.contains(phoneNumber))
            	  phoneNumbers.add(phoneNumber);
            }
            Bundle bundle = new Bundle();
            bundle.putString(NAME, name);
            bundle.putStringArrayList(PHONE, phoneNumbers);
            
            
            if(phoneNumbers.size() > 1){
            	showDialog(DIALOG_NUMBER_LIST, bundle);
            }else{
            	ContactItem item = new ContactItem(contactId, name, phoneNumbers.get(0));
            	System.out.println("contactId "+contactId);
            	if(!checked){
            		Utils.addContact(contactId, item);
            		System.out.println("Contact Added ");
            	}else{
            		System.out.println("Removing contacts");
            		Utils.removeContact(contactId, item);
            	}
            	
            }
            System.out.println("On Item Selected :: Selected Contacts :: "+Utils.getSelectedContacts());
            
	}
	int contactId = 0;
	
	@Override
	protected void onPrepareDialog(int id, Dialog dialog, Bundle args) {
		// TODO Auto-generated method stub
		switch (id) {
		case DIALOG_NUMBER_LIST:
			final String[] phones =  new String[args.getStringArrayList(PHONE).size()];
			args.getStringArrayList(PHONE).toArray(phones);
			((NumberListDialog)dialog).updateGroup(this, args.getString(NAME), phones, contactId);
			break;

		default:
			super.onPrepareDialog(id, dialog, args);
		
	break;
		}
	}
	
	@Override
	protected Dialog onCreateDialog(int id, Bundle args) {
		// TODO Auto-generated method stub
		Dialog dialog = null;
		switch (id) {
		case DIALOG_NUMBER_LIST:
			final String[] phones =  new String[args.getStringArrayList(PHONE).size()];
			args.getStringArrayList(PHONE).toArray(phones);
			dialog = new NumberListDialog(this, "Select Contact(s)", phones , contactId); 
			
			break;
		case DIALOG_CLEAR_DATA_ALERT:
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Alert");
			builder.setMessage("Do you want to clear all the selected contacts ?");
			builder.setNegativeButton("No", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.cancel();
				}});
		
	builder.setPositiveButton("Yes", new DialogInterface.OnClickListener(){

				@Override
				public void onClick(DialogInterface dialog, int which) {
					// TODO Auto-generated method stub
					dialog.cancel();
					Utils.getSelectedContacts().clear();
					finish();
				}});
			dialog = builder.create();
			break;
		default:
			dialog = super.onCreateDialog(id, args);
			break;
		}
		return  dialog;
	}
	
	/*public void toggleView(boolean state){
		System.out.println(" before toggle "+selectedView.isChecked());
		selectedView.setSelected(state);
		System.out.println(" After toggle "+selectedView.isChecked());
		System.out.println(Utils.getSelectedContacts());
		getListView().invalidateViews();
	}*/
	
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO Auto-generated method stub
		System.out.println(" on key down ");
		if(keyCode == KeyEvent.KEYCODE_BACK && Utils.getSelectedContacts().size() > 0){
			System.out.println(" if ...");
			showDialog(DIALOG_CLEAR_DATA_ALERT);
			return false;
		}else{
			System.out.println(" else..");
		
	return super.onKeyDown(keyCode, event);
		}
	}
	
}
